// pages/teacher/sign_result.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fpath: null,
    showView: false,
    currentTab: 0,
    signnum: 0,
    unsignnum: 0,
    totalnum: 0,
    userList: [],
    unsignUserList: [],
    // 页面垂直滑动的距离
    scrollTop: undefined,
    unsignTip: true,
    classListHistory: [],
    loading: {
      type: 'flip',
      show: true,
      size: 'medium',
      color: '#e54d42',
      name: 'flip'
    },
    types: [
      "未认证",
      "旷课",
      "迟到",
      "请假",
      "其他"
    ],
    typeIndex: 0,
    state: '',
    lid: 1,
    signtitle: '软件工程实践'
  },

  onPageScroll(res) {
    this.setData({
      scrollTop: res.scrollTop
    })
  },

  onLoad: async function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.data.lid = options.lid
    await this.getSign()
    await this.getUnsign()
  },

  // 返回已签到结果（教师端）
  async getSign() {
    const {
      data: res
    } = await wx.$http.get('/rec/resultTeacher', {
      lid: this.data.lid
    }, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      wx.showToast({
        title: res.message,
        icon: "none"
      })
    } else {
      this.setData({
        signtitle: res.data[0],
        userList: res.data[2],
        signnum: res.data[2].length
      })
    }
  },

  async getUnsign() {
    const {
      data: res
    } = await wx.$http.get('/rec/noSignInTea', {
      lid: this.data.lid
    }, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      // wx.showToast({
      //   title: "获取结果失败",
      //   icon: "none"
      // })
      if (res.code == 197) {
        this.setData({
          unsignTip: false
        })
      }
    } else {
      var total = this.data.signnum
      this.setData({
        unsignUserList: res.data[2],
        unsignnum: res.data[2].length,
        totalnum: total + res.data[2].length
      })
    }
  },
  //改变代签到类型 
  bindTypeChange: function (e) {
    var newstate = this.data.types[e.detail.value]
    this.setData({
      typeIndex: e.detail.value,
      state: newstate
    })
    this.signin(e)
  },
  signin: async function (e) {
    await wx.User.recByTea({
      data: {
        lid: this.data.lid,
        uid: e.currentTarget.dataset.uid,
        state: this.data.state
      }
    })
    wx.showToast({
      title: wx.getStorageSync('recByTea'),
      icon: 'none'
    })
    await this.getSign()
    this.getUnsign()
  },

  //改变签到类型
  resultTypeChange: async function(e){
    await wx.User.setSignInState({
      data: {
        uid: e.currentTarget.dataset.uid,
        lid: this.data.lid,
        state: this.data.types[e.detail.value]
      },
    })
    await this.getSign()
    this.getUnsign()
  },

  //点击上传获取历史名单
  getClassListHistory: async function () {
    this.setData({
      showView: !this.data.showView
    })
    await wx.User.classListHistory({
      data: {
        uid: wx.getStorageSync('userinfo').uid
      },
    })
    this.setData({
      classListHistory: wx.getStorageSync('classFile')
    })
  },

  //删除历史名单
  deleteListFile: async function (e) {
    await wx.User.deleteListFile({
      data: {
        uid: wx.getStorageSync('userinfo').uid,
        id: parseInt(e.currentTarget.dataset.id),
        filePath: e.currentTarget.dataset.path,
      },
    })
    await wx.User.classListHistory({
      data: {
        uid: wx.getStorageSync('userinfo').uid
      },
    })
    this.setData({
      classListHistory: wx.getStorageSync('classFile')
    })

  },

  //对比签到名单
  contrast: async function (e) {
    this.setData({
      showView: !this.data.showView,
      fpath: e.currentTarget.dataset.fpath
    })
    await wx.User.contrast({
      data: {
        filePath: this.data.fpath,
        lid: this.data.lid,
      }
    })
    await this.getSign()
    this.setData({
      unsignUserList: wx.getStorageSync('unSignList'),
      unsignnum: wx.getStorageSync('unSignList').length
    })
  },

  //上传新签到名单
  uploadNewFile: function () {
    return new Promise((resolve, reject) => {
      var path;
      var fileName;
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          path = res.tempFiles[0].path
          fileName = res.tempFiles[0].name
          wx.uploadFile({
            url: 'https://www.xqzjgsu.xyz/fss/class/uploadClassList',
            filePath: path,
            name: 'list',
            header: {
              'content-type': 'multipart/form-data',
              'Authorization': 'Bearar ' + wx.getStorageSync('token')
            },
            formData: {
              uid: wx.getStorageSync('userinfo').uid,
              fileName: fileName
            },
            success: function (res) {
              resolve(true)
              var json = JSON.parse(res.data)
              if (json.code == 200) {
                wx.showToast({
                  title: json.message,
                  icon: "success"
                })
              } else {
                wx.showToast({
                  title: json.message,
                  icon: 'none'
                })
              }
            }
          })
        }
      })
    })

  },
  upload: async function () {
    await this.uploadNewFile();
    await wx.User.classListHistory({
      data: {
        uid: wx.getStorageSync('userinfo').uid
      },
    })
    this.setData({
      classListHistory: wx.getStorageSync('classFile')
    })
  },

  // 下载文件
  excel: function (e) {
    wx.setClipboardData({
      // data: 'https://www.xqzjgsu.xyz:8077/fss/rec/excel?lid=' + this.data.lid,
      data: 'https://www.xqzjgsu.xyz/fss/rec/excel?lid=' + this.data.lid,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showModal({
              title: '提示',
              content: '下载链接已复制到粘贴板，请打开浏览器下载文件',
              confirmColor: '#0bc183',
              confirmText: '知道了',
              showCancel: false
            })
          }
        })
      }
    })
  },

  // wx.downloadFile({
  //   url: 'http://47.103.218.55:8077/fss/rec/excel?lid=' + this.data.lid,
  //   success(res) {
  //     console.log(res)
  //     var savePath = wx.env.USER_DATA_PATH + "/123.xls"
  //     wx.getFileSystemManager()
  //       .saveFile({ 
  //         tempFilePath: res.tempFilePath,
  //         filePath: savePath,
  //         success(res2) {
  //           wx.saveImageToPhotosAlbum({
  //             filePath: savePath,
  //             success: (res) => {
  //               wx.showModal({
  //                 title: '文件已保存到手机相册',
  //                 content: '位于tencent/MicroMsg/WeiXin下 \r\n将保存的文件重命名改为[ .docx ]后缀即可',
  //                 confirmColor: '#0bc183',
  //                 confirmText: '知道了',
  //                 showCancel: false
  //               })
  //             },
  //             fail(res) {
  //               console.log(res)
  //             }
  //           })
  //         },
  //         fail(res) {
  //           console.log(res)
  //         }
  //       })
  //   },
  // })
  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },

  navtodata() {
    if (this.data.lid == 0) {
      wx.showToast({
        title: 'Error',
      })
      return;
    }
    // wx.navigateTo({
    //   url: './signdata?lid-' + this.data.lid,
    // })
    wx.navigateTo({
      url: './signdata?signnum=' + this.data.signnum + '&unsignnum=' + this.data.unsignnum + '&totalnum=' + this.data.totalnum,
    })
  },


  //点击切换
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
})